package io.renren.modules.welderinfo.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.modules.testrestful.entity.DevicesInfoResponse;
import io.renren.modules.testrestful.entity.SendWs;
import io.renren.modules.testrestful.entity.User;
import io.renren.modules.testrestful.service.impl.UsersServiceImpl;
import io.renren.modules.welderinfo.entity.WeldorData;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.welderinfo.dao.WelderinfoDao;
import io.renren.modules.welderinfo.entity.WelderinfoEntity;
import io.renren.modules.welderinfo.service.WelderinfoService;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service("welderinfoService")
public class WelderinfoServiceImpl extends ServiceImpl<WelderinfoDao, WelderinfoEntity> implements WelderinfoService {

    @Autowired
    WelderinfoDao welderinfoDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WelderinfoEntity> page = this.page(
                new Query<WelderinfoEntity>().getPage(params),
                new QueryWrapper<WelderinfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<WelderinfoEntity> getwelderinfo(String welderId, String welderName, String groupName, String cardType) {
        return welderinfoDao.getwelderinfo(welderId,welderName,groupName,cardType);
    }

    @Data
    public static class  ReHeader{
        private String key;
    }

    @Autowired
    private RestTemplate restTemplate;
//        @Scheduled(cron = "0/5 * * * * ?")
    public Object getWeldToken() throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();

        // 获取token
//        UsersServiceImpl.ReHeader reHeader = new UsersServiceImpl.ReHeader();
        WelderinfoServiceImpl.ReHeader reHeader = new WelderinfoServiceImpl.ReHeader();
        reHeader.setKey("cmhi2023");
        String url = "http://10.142.3.129:8080/getOpenApiToken";
        String result = restTemplate.postForObject(url,reHeader, String.class);
//       System.out.println(result);
//        System.out.println("----------------");
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(result);
        String token = String.valueOf(jsonNode.get("data").get("token")).replace("\"","");
//        System.out.println("以下是焊机");
//        System.out.println(token);

        return token.toString();
    }

    //获取焊工信息
//    @Async("screenTaskExecutor")
//    @Scheduled(cron = "0/5 * * * * ?")
    public String getWeldorInfo() throws InterruptedException, JsonProcessingException, URISyntaxException {
        String url = "http://10.142.3.129:8080/system/weldorinfo/list";
//        String url = "http://localhost:8089/renren-fast/users/123";

        String token=getWeldToken().toString();
        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setBearerAuth(token);
//        httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
//        System.out.println(httpHeaders);
        RequestEntity<Void> requestEntity = new RequestEntity<>(httpHeaders,HttpMethod.GET,new URI(url));
        ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity,
                String.class);
//        System.out.println("responseEntity");
//        System.out.println(responseEntity);
        String weldorinfo = responseEntity.getBody();
//        System.out.println(weldorinfo);
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(weldorinfo);
            JsonNode rowsNode = jsonNode.get("rows");
            if(!jsonNode.isArray()){
                for (JsonNode rowNode:rowsNode) {
                    String welderid = String.valueOf(Long.valueOf(rowNode.get("weldorId").asText()));
                    String weldername = rowNode.get("weldorName").asText();
                    String weldercard = rowNode.get("weldorCardNo").asText();
                    String dept = rowNode.get("sysDept").get("deptName").asText();
                    String groupname = rowNode.get("welGroupinfo").get("groupName").asText();
                    String techlevel = rowNode.get("weldorTechlevel").asText();
                    String birthdayString = rowNode.get("birthday").asText();
                    Date birthday = null;
                    if (!"null".equals(birthdayString)) {
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        birthday = format.parse(birthdayString);
                    }
                    String cardtype = rowNode.get("delFlag").asText();
                    System.out.println("id:"+welderid);
                    System.out.println("name:"+weldername);
                    System.out.println("name:"+weldercard);
                    System.out.println("name:"+dept);
                    System.out.println("name:"+groupname);
                    System.out.println("name:"+techlevel);
                    System.out.println("name:"+birthday);
                    System.out.println("name:"+cardtype);
                    System.out.println("------------------");

                    WelderinfoEntity welderinfoEntity = new WelderinfoEntity();
                    welderinfoEntity.setWelderid(welderid);
                    welderinfoEntity.setWeldername(weldername);
                    welderinfoEntity.setWeldercard(weldercard);
                    welderinfoEntity.setDept(dept);
                    welderinfoEntity.setGroupname(groupname);
                    welderinfoEntity.setTechlevel(techlevel);
                    welderinfoEntity.setBirthday(birthday);
                    welderinfoEntity.setCardtype(cardtype);
                    saveMysql(welderinfoEntity);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return responseEntity.toString();
    }

    public void saveMysql(WelderinfoEntity welderinfoEntity){
        String welderid = String.valueOf(welderinfoEntity.getWelderid());
        int count = welderinfoDao.countByWelderId(welderid);
        if(count>0){
            System.out.println("已经存在");
        } else {
            welderinfoDao.addWelder(welderinfoEntity);
        }
        System.out.println("save");
//        log.info("save");
    }

}